﻿using CocoaAni.Net.WebSockets.Messages;
using CocoaAni.Net.WebSockets.Tools;
using System.Reflection;
using CocoaAni.Net.WebSockets.Exceptions;
using CocoaAni.Net.WebSockets.Server.Exceptions;
using WebSocketControllerAttribute = CocoaAni.Net.WebSockets.Server.Attributes.WebSocketControllerAttribute;

namespace CocoaAni.Net.WebSockets.Server.Controllers;

[WebSocketController]
public abstract class WebSocketController
{
    public string MapPath { get; private set; }

    protected WebSocketController()
    {
        var thisType = this.GetType();
        var attr = thisType.GetCustomAttribute<WebSocketControllerAttribute>();
        if (attr == null)
        {
            throw new NotSupportedException("Not Found Attribute [WebSocketController]");
        }
        var path = attr.Path.Contains(WebSocketControllerAttribute.PathIsSelfName)
            ? attr.Path.Replace(
                WebSocketControllerAttribute.PathIsSelfName,
                thisType.Name.Replace("Controller", ""))
            : attr.Path;
        MapPath = path.StartsWith("/") ? path.ToLower().Trim() : "/" + path.ToLower().Trim();
        // CollectHandlers();
    }

    public virtual void OnHandShake(WSHandShakeRequest req, WSHandShakeResponse resp)
    {
        
    }

    public virtual object OnPing(WebSocketContext context)
    {
        return "Pong";
    }

    public virtual void OnConnecting(WebSocketContext context)
    { }

    public virtual void OnClosed(WebSocketContext context)
    { }

    public virtual object? OnOpen(WebSocketContext context)
    {
        return null;
    }

    public virtual void OnCloseReceived(WebSocketContext context)
    { }
    public virtual object? OnMessageArgError(WebSocketContextException ex)
    {
        return $"{{\"code\": -1,\"message\": \"参数错误：{ex.Context!.MessageArgContext.ArgDefineInfo.Name}\"}}";
    }
}